package com.newcoin.xgbtask.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.newcoin.xgbtask.entity.*;
import com.newcoin.xgbtask.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;

@Service
@Slf4j
public class TaskService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private XgbBonusMapper bonusMapper;

    @Autowired
    private XgbUsersMapper usersMapper;

    @Autowired
    private XgbFinancialOrderMapper financialOrderMapper;

    @Autowired
    private XgbBonusRecordMapper recordMapper;


    //@Scheduled(cron = "0 0 0/2 * * ?")
    @Scheduled(cron = "0 0 2 * * ?")
    //@Scheduled(fixedDelay = 10000000)
    @Transactional(rollbackFor = Exception.class)
    public void incomeDistribution() {
        List<XgbFinancialOrder> list = financialOrderMapper.selectList(new QueryWrapper<XgbFinancialOrder>()
                .last("WHERE end_date<=UNIX_TIMESTAMP(NOW())"));
        for (XgbFinancialOrder order : list) {
            List<XgbFinancialOrder> l = financialOrderMapper.selectList(new QueryWrapper<XgbFinancialOrder>()
                    .eq("id", order.getId())
                    .eq("state", 0));
            for (XgbFinancialOrder o : l){
                int row = financialOrderMapper.update(null, new UpdateWrapper<XgbFinancialOrder>()
                        .eq("id", o.getId())
                        .set("state", 1));
                row =row + accountMapper.update(null,new UpdateWrapper<XgbAccount>()
                        .eq("user_id",o.getUserId())
                        .setSql("balance=balance+" + o.getAmount())
                        .setSql("financial_balance=financial_balance-" + o.getAmount()));
            }


            /*int row = financialOrderMapper.update(null, new UpdateWrapper<XgbFinancialOrder>()
                    .eq("id", order.getId())
                    .eq("state", 0)
                    .set("state", 1)
                    .setSql("financial_balance=financial_balance-" + order.getAmount()));*/
            /*BigDecimal staticBonus = order.getAmount().multiply(new BigDecimal(order.getDay())).multiply(order.getProportion());
            accountMapper.update(null, new UpdateWrapper<XgbAccount>()
                    .eq("user_id", order.getUserId())
                    .gt("financial_balance", order.getAmount())
                    .setSql("financial_balance=financial_balance-" + order.getAmount())
            );*/
        }
            /*log.info("订单{}到期更新状态{}", order.getId(), row == 1 ? "成功" : "失败");
            BigDecimal staticBonus = order.getAmount().multiply(new BigDecimal(order.getDay())).multiply(order.getProportion());
            XgbBonusRecord bonusRecord = new XgbBonusRecord();
            bonusRecord.setUserId(order.getUserId());
            bonusRecord.setAmount(staticBonus);
            bonusRecord.setBonusName("理财收益");
            bonusRecord.setType(0);
            row = row + recordMapper.insert(bonusRecord);*/

           /*     row = row + accountMapper.update(null, new UpdateWrapper<XgbAccount>()
                        .eq("user_id", order.getUserId())
                        .gt("financial_balance", order.getAmount())
                        .setSql("balance=balance+" + staticBonus.add(order.getAmount()))
                        .setSql("financial_balance=financial_balance-" + order.getAmount())
                        .setSql("cumulative_total_income=cumulative_total_income+" + staticBonus)
                        .setSql("financial_total_income=financial_total_income+" + staticBonus)
                        .setSql("financial_static_total_income=financial_static_total_income+" + staticBonus)
                        .setSql("financial_today_total_income=financial_today_total_income+" + staticBonus)
                        .setSql("financial_today_static_income=financial_today_static_income+" + staticBonus)
                );*/
            /*if (row != 3) {
                throw new RuntimeException("奖金出错");
            }*/
            /*List<XgbFinancialOrder> list1 = financialOrderMapper.selectList(new QueryWrapper<XgbFinancialOrder>()
                    .last("WHERE end_date>UNIX_TIMESTAMP(NOW())"));
            for (XgbFinancialOrder order1 : list1) {
                BigDecimal staticeveryBonus = order1.getAmount().multiply(order1.getProportion()).divide(new BigDecimal(order1.getDay()), 5);
                XgbBonusRecord br = new XgbBonusRecord();
                br.setUserId(order1.getUserId());
                br.setAmount(staticeveryBonus);
                br.setBonusName("每日理财收益");
                br.setType(5);
                row = row + recordMapper.insert(br);*/

                /*XgbUsers users = usersMapper.selectById(order.getUserId());
                if (!StringUtils.isEmpty(users.getPath())) {
                    String[] paths = users.getPath().split(",");
                    for (int i = paths.length - 1; i >= paths.length - 3 && i > -1; i--) {
                        XgbBonus bonusSetting = bonusMapper.selectById(paths.length - i);
                        Integer userId = Integer.valueOf(paths[i]);
                        if (userId.compareTo(new Integer("0")) == 0 || userId.compareTo(new Integer("1")) == 0) {
                            continue;
                        }
                        BigDecimal dynamicBonus = staticBonus.multiply(bonusSetting.getProportion());
                        XgbBonusRecord bonusRecord1 = new XgbBonusRecord();
                        bonusRecord1.setUserId(userId);
                        bonusRecord1.setAmount(dynamicBonus);
                        bonusRecord1.setBonusName("理财" + (paths.length - i) + "代收益");
                        bonusRecord1.setType(2);
                        int row1 = recordMapper.insert(bonusRecord1);
                        row1 = row1 + accountMapper.update(null, new UpdateWrapper<XgbAccount>()
                                .eq("user_id", userId)
                                .setSql("balance=balance+" + dynamicBonus)
                                .setSql("cumulative_total_income=cumulative_total_income+" + dynamicBonus)
                                .setSql("financial_total_income=financial_total_income+" + dynamicBonus)
                                .setSql("financial_dynamic_total_income=financial_dynamic_total_income+" + dynamicBonus)
                                .setSql("financial_today_total_income=financial_today_total_income+" + dynamicBonus)
                                .setSql("financial_today_dynamic_income=financial_today_dynamic_income+" + dynamicBonus)
                        );
                        if (row1 != 2) {
                            throw new RuntimeException("动态奖金出错");
                        }
                    }
                }*/
            }



    @Scheduled(cron = "0 0 6 * * ?")
    //@Scheduled(cron="0 0/1 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void everydayincome() {
        List<XgbFinancialOrder> list = financialOrderMapper.selectList(new QueryWrapper<XgbFinancialOrder>()
                .last("WHERE end_date>UNIX_TIMESTAMP(NOW())"));
        for (XgbFinancialOrder order : list) {
            BigDecimal staticeveryBonus = (order.getAmount().multiply(order.getProportion()));
            XgbBonusRecord br = new XgbBonusRecord();
            br.setUserId(order.getUserId());
            br.setAmount(staticeveryBonus);
            br.setBonusName("每日理财收益");
            br.setType(5);
            recordMapper.insert(br);
            accountMapper.update(null, new UpdateWrapper<XgbAccount>()
                    .eq("user_id", order.getUserId())
                    //.gt("financial_balance", order.getAmount())
                    .setSql("balance=balance+" + staticeveryBonus)
                    //.setSql("balance=balance+" + staticeveryBonus.add(order.getAmount()))
                    //.setSql("financial_balance=financial_balance-" + order.getAmount())
                    //.setSql("financial_balance=financial_balance+" + staticeveryBonus)
                    .setSql("cumulative_total_income=cumulative_total_income+" + staticeveryBonus)
                    .setSql("financial_total_income=financial_total_income+" + staticeveryBonus)
                    .setSql("financial_static_total_income=financial_static_total_income+" + staticeveryBonus)
                    .setSql("financial_today_total_income=financial_today_total_income+" + staticeveryBonus)
                    .setSql("financial_today_static_income=financial_today_static_income+" + staticeveryBonus)
            );
        }
    }


    @Scheduled(cron = "0 55 23 * * ?")
    public void reset() {
        int row = accountMapper.update(null, new UpdateWrapper<XgbAccount>()
                .setSql("financial_yesterday_total_income=financial_today_total_income")
                .setSql("financial_yesterday_dynamic_income=financial_today_dynamic_income")
                .setSql("financial_yesterday_static_income=financial_today_static_income")
                .setSql("order_grab_yesterday_total_income=order_grab_today_total_income")
                .setSql("order_grab_yesterday_dynamic_income=order_grab_today_dynamic_income")
                .setSql("order_grab_yesterday_static_income=order_grab_today_static_income")
                .setSql("proxy_yesterday_total_income=proxy_today_total_income")
                .setSql("proxy_yesterday_dynamic_income=proxy_today_dynamic_income")
                .setSql("proxy_yesterday_static_income=proxy_today_static_income"));
        log.info("统计昨日收益{}", row);
        int row1 = accountMapper.update(null, new UpdateWrapper<XgbAccount>()
                .set("financial_today_total_income", 0)
                .set("financial_today_dynamic_income", 0)
                .set("financial_today_static_income", 0)
                .set("order_grab_today_total_income", 0)
                .set("order_grab_today_dynamic_income", 0)
                .set("order_grab_today_static_income", 0)
                .set("proxy_today_total_income", 0)
                .set("proxy_today_dynamic_income", 0)
                .set("proxy_today_static_income", 0));
        log.info("重置今日收益{}", row1);
    }
}
